package com.learn.learnsystem.config;

import com.learn.learnsystem.filter.JwtAuthenticationFilter;
import com.learn.learnsystem.utils.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    private final JwtTokenUtil jwtTokenUtil;
    private final UserDetailsService userDetailsService; // 新增依赖
    // 必须添加的依赖项
    private final AuthenticationConfiguration authenticationConfiguration;

    // 白名单路径列表
    private static final String[] WHITE_LIST = {
            "/api/auth/login",          // 登录接口
            "/login/**",          // 登录接口
//            "/user/**",          // user接口
            "/api/auth/register",       // 注册接口
            "/v3/api-docs/**",          // Swagger 文档
            "/swagger-ui/**",           // Swagger UI
            "/swagger-resources/**",    // Swagger 资源
            "/webjars/**",              // Webjars
            "/doc.html",                // 兼容新版 Swagger
            "/favicon.ico",             // 网站图标
            "/error",                   // 错误端点
            "/static/**",               // 静态资源
            "/index.html"               // 前端入口
    };

    // 新版本的spring，路径都要使用/*通配符，不能使用/**
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())  // 禁用 CSRF
                .cors(Customizer.withDefaults()) // 启用默认 CORS 配置
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.OPTIONS,"/*").permitAll() // 允许 OPTIONS 请求
                        .requestMatchers(WHITE_LIST).permitAll() // 白名单路径
                        .requestMatchers("/*/../*").denyAll()// 防止目录遍历攻击
//                        .requestMatchers(HttpMethod.DELETE, "/**").denyAll()// 禁用危险 HTTP 方法
//                        .requestMatchers(HttpMethod.TRACE, "/**").denyAll()// 禁用危险 HTTP 方法
//                                .requestMatchers("/api/admin/**").hasRole("ADMIN") //接口权限分层 管理员接口
//                                .requestMatchers("/api/user/**").hasAnyRole("USER", "ADMIN") //接口权限分层 普通用户
                        .anyRequest().authenticated() // 其他所有请求需要认证
                )

                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话
                )
                .addFilterBefore(  // 修改为使用构造函数注入
                        new JwtAuthenticationFilter(jwtTokenUtil, userDetailsService),
                        UsernamePasswordAuthenticationFilter.class
                );

        return http.build();
    }
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}